#include "gallery.h"
#include "lcd.h"
#include "bmp.h"
#include "ts.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>

// 全局变量
static photo_info_t g_photos[MAX_PHOTOS];
static int g_photo_count = 0;
static int g_current_page = 0;
static int g_total_pages = 0;

/**
 * @brief 初始化相册目录
 */
int gallery_init()
{
  struct stat st = {0};

  // 检查目录是否存在
  if (stat(GALLERY_DIR, &st) == -1)
  {
    // 目录不存在，创建它
#ifdef _WIN32
    if (mkdir(GALLERY_DIR) == -1)
#else
    if (mkdir(GALLERY_DIR, 0755) == -1)
#endif
    {
      perror("创建相册目录失败");
      return -1;
    }
    printf("相册目录已创建: %s\n", GALLERY_DIR);
  }

  return 0;
}

/**
 * @brief 保存YUYV图像为BMP文件
 */
static int save_yuyv_as_bmp(unsigned char *yuyv_data, int width, int height, const char *filename)
{
  FILE *fp = fopen(filename, "wb");
  if (!fp)
  {
    perror("打开文件失败");
    return -1;
  }

  // BMP文件头
  unsigned char bmp_header[54] = {
      'B', 'M',    // 文件类型
      0, 0, 0, 0,  // 文件大小（稍后填充）
      0, 0, 0, 0,  // 保留字段
      54, 0, 0, 0, // 数据偏移
      40, 0, 0, 0, // 信息头大小
      0, 0, 0, 0,  // 宽度（稍后填充）
      0, 0, 0, 0,  // 高度（稍后填充）
      1, 0,        // 颜色平面数
      24, 0,       // 每像素位数
      0, 0, 0, 0,  // 压缩方式
      0, 0, 0, 0,  // 图像大小
      0, 0, 0, 0,  // 水平分辨率
      0, 0, 0, 0,  // 垂直分辨率
      0, 0, 0, 0,  // 颜色数
      0, 0, 0, 0   // 重要颜色数
  };

  // 计算行字节数（必须是4的倍数）
  int row_size = ((width * 3 + 3) / 4) * 4;
  int image_size = row_size * height;
  int file_size = 54 + image_size;

  // 填充文件大小
  *(int *)(bmp_header + 2) = file_size;
  // 填充宽度和高度
  *(int *)(bmp_header + 18) = width;
  *(int *)(bmp_header + 22) = height;
  // 填充图像大小
  *(int *)(bmp_header + 34) = image_size;

  // 写入BMP头
  fwrite(bmp_header, 1, 54, fp);

  // 分配行缓冲区
  unsigned char *row_buffer = (unsigned char *)malloc(row_size);
  if (!row_buffer)
  {
    fclose(fp);
    return -1;
  }

  // 转换YUYV到BGR并写入（BMP是从底部到顶部存储）
  for (int y = height - 1; y >= 0; y--)
  {
    memset(row_buffer, 0, row_size);

    for (int x = 0; x < width; x++)
    {
      int yuyv_index = (y * width + x) * 2;
      int Y, U, V;

      if (x % 2 == 0)
      {
        Y = yuyv_data[yuyv_index];
        U = yuyv_data[yuyv_index + 1];
        V = yuyv_data[yuyv_index + 3];
      }
      else
      {
        Y = yuyv_data[yuyv_index];
        U = yuyv_data[yuyv_index - 1];
        V = yuyv_data[yuyv_index + 1];
      }

      // YUV to RGB conversion
      int C = Y - 16;
      int D = U - 128;
      int E = V - 128;

      int R = (298 * C + 409 * E + 128) >> 8;
      int G = (298 * C - 100 * D - 208 * E + 128) >> 8;
      int B = (298 * C + 516 * D + 128) >> 8;

      // 限制范围
      R = R < 0 ? 0 : (R > 255 ? 255 : R);
      G = G < 0 ? 0 : (G > 255 ? 255 : G);
      B = B < 0 ? 0 : (B > 255 ? 255 : B);

      // BGR顺序
      row_buffer[x * 3] = B;
      row_buffer[x * 3 + 1] = G;
      row_buffer[x * 3 + 2] = R;
    }

    fwrite(row_buffer, 1, row_size, fp);
  }

  free(row_buffer);
  fclose(fp);
  return 0;
}

/**
 * @brief 保存截屏到相册
 */
int gallery_save_photo(unsigned char *yuyv_data, int width, int height)
{
  if (!yuyv_data)
  {
    return -1;
  }

  // 初始化相册目录
  gallery_init();

  // 生成文件名（使用时间戳）
  time_t now = time(NULL);
  struct tm *tm_info = localtime(&now);
  char filename[256];
  snprintf(filename, sizeof(filename), "%s/photo_%04d%02d%02d_%02d%02d%02d.bmp",
           GALLERY_DIR,
           tm_info->tm_year + 1900,
           tm_info->tm_mon + 1,
           tm_info->tm_mday,
           tm_info->tm_hour,
           tm_info->tm_min,
           tm_info->tm_sec);

  printf("保存照片: %s\n", filename);

  // 保存为BMP文件
  if (save_yuyv_as_bmp(yuyv_data, width, height, filename) < 0)
  {
    fprintf(stderr, "保存照片失败\n");
    return -1;
  }

  printf("照片已保存: %s\n", filename);
  return 0;
}

/**
 * @brief 扫描相册目录获取照片列表
 */
int gallery_scan_photos(photo_info_t *photos, int max_count)
{
  DIR *dir = opendir(GALLERY_DIR);
  if (!dir)
  {
    perror("打开相册目录失败");
    return 0;
  }

  int count = 0;
  struct dirent *entry;

  while ((entry = readdir(dir)) != NULL && count < max_count)
  {
    // 只处理.bmp文件
    if (strstr(entry->d_name, ".bmp") == NULL)
    {
      continue;
    }

    // 获取文件信息
    char filepath[512];
    snprintf(filepath, sizeof(filepath), "%s/%s", GALLERY_DIR, entry->d_name);

    struct stat st;
    if (stat(filepath, &st) == 0)
    {
      strncpy(photos[count].filename, entry->d_name, sizeof(photos[count].filename) - 1);
      photos[count].timestamp = st.st_mtime;
      count++;
    }
  }

  closedir(dir);

  // 按时间戳降序排序（最新的在前面）
  for (int i = 0; i < count - 1; i++)
  {
    for (int j = i + 1; j < count; j++)
    {
      if (photos[i].timestamp < photos[j].timestamp)
      {
        photo_info_t temp = photos[i];
        photos[i] = photos[j];
        photos[j] = temp;
      }
    }
  }

  return count;
}

/**
 * @brief 绘制缩略图
 */
static void draw_thumbnail(const char *photo_path, int grid_x, int grid_y)
{
  // 计算屏幕位置 (增加左边距和上边距)
  int left_margin = 20;
  int top_margin = 20;
  int screen_x = left_margin + grid_x * (THUMBNAIL_WIDTH + THUMBNAIL_SPACING);
  int screen_y = top_margin + grid_y * (THUMBNAIL_HEIGHT + THUMBNAIL_SPACING);

  // 绘制边框
  lcd_draw_rect(screen_x - 2, screen_y - 2, THUMBNAIL_WIDTH + 4, THUMBNAIL_HEIGHT + 4, 0x404040);

  // 显示缩放后的缩略图
  bmp_display_scaled(photo_path, screen_x, screen_y, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
}

/**
 * @brief 绘制相册界面
 */
static void draw_gallery_ui(int page)
{
  // 清空屏幕
  // lcd_clear(0x000000);
  bmp_display("./blank.bmp", 0, 0);

  // 显示标题
  // 这里可以添加标题显示代码

  // 计算当前页的照片范围
  int start_index = page * (GALLERY_COLS * GALLERY_ROWS);
  int end_index = start_index + (GALLERY_COLS * GALLERY_ROWS);
  if (end_index > g_photo_count)
  {
    end_index = g_photo_count;
  }

  // 显示缩略图
  int photo_index = start_index;
  for (int row = 0; row < GALLERY_ROWS && photo_index < end_index; row++)
  {
    for (int col = 0; col < GALLERY_COLS && photo_index < end_index; col++)
    {
      char photo_path[512];
      snprintf(photo_path, sizeof(photo_path), "%s/%s",
               GALLERY_DIR, g_photos[photo_index].filename);

      draw_thumbnail(photo_path, col, row);
      photo_index++;
    }
  }

  // 绘制页码指示器 (底部中间)
  if (g_total_pages > 1)
  {
    // 绘制页码背景
    int indicator_y = 420;
    int indicator_width = g_total_pages * 20;
    int indicator_x = (800 - indicator_width) / 2;

    // 绘制所有页码点
    for (int i = 0; i < g_total_pages; i++)
    {
      int dot_x = indicator_x + i * 20 + 5;
      int dot_color = (i == page) ? 0xFFFFFF : 0x404040; // 当前页白色，其他页灰色
      lcd_draw_rect(dot_x, indicator_y, 10, 10, dot_color);
    }
  }
}

/**
 * @brief 全屏显示照片
 */
int gallery_show_fullscreen(const char *photo_path)
{
  extern int g_running; // 全局退出标志

  // 清空屏幕
  bmp_display("./blank.bmp", 0, 0);

  // 全屏显示照片
  // bmp_display(photo_path, 0, 0);
  bmp_display_scaled(photo_path, 0, 0, 800, 480);

  // 等待触摸返回
  ts_point pt;
  while (g_running)
  {
    // 检查Ctrl+C信号
    if (!g_running)
    {
      printf("\n检测到Ctrl+C信号，退出全屏模式...\n");
      break;
    }

    get_ts_point(&pt);

    // 任意位置点击返回
    break;
  }

  return 0;
}

/**
 * @brief 显示相册界面
 */
int gallery_show()
{
  printf("打开相册...\n");

  // 初始化相册
  gallery_init();

  // 扫描照片
  g_photo_count = gallery_scan_photos(g_photos, MAX_PHOTOS);
  printf("找到 %d 张照片\n", g_photo_count);

  if (g_photo_count == 0)
  {
    printf("相册为空\n");
    // 显示提示信息
    bmp_display("./blank.bmp", 0, 0);
    // 这里可以显示"相册为空"的提示
    sleep(2);
    return 0;
  }

  // 计算总页数
  g_total_pages = (g_photo_count + GALLERY_COLS * GALLERY_ROWS - 1) / (GALLERY_COLS * GALLERY_ROWS);
  g_current_page = 0;

  // 显示相册界面
  draw_gallery_ui(g_current_page);

  // 触摸交互循环
  ts_point pt;
  int running = 1;
  extern int g_running; // 全局退出标志（Ctrl+C信号）

  while (running && g_running)
  {
    // 检查Ctrl+C信号
    if (!g_running)
    {
      printf("\n检测到Ctrl+C信号，退出相册...\n");
      break;
    }

    get_ts_point(&pt);
    printf("相册触摸: x=%d, y=%d\n", pt.x, pt.y);

    // 返回按钮 (右上角: 780-800, 0-20)
    if (pt.x >= 780 && pt.x <= 800 && pt.y >= 0 && pt.y <= 20)
    {
      printf("点击返回按钮\n");
      break;
    }
    // 点击缩略图区域
    else if (pt.y < 460)
    {
      // 计算点击的是哪张照片
      int left_margin = 20;
      int top_margin = 20;

      // 检查是否在有效区域内
      if (pt.x >= left_margin && pt.y >= top_margin)
      {
        int relative_x = pt.x - left_margin;
        int relative_y = pt.y - top_margin;

        int col = relative_x / (THUMBNAIL_WIDTH + THUMBNAIL_SPACING);
        int row = relative_y / (THUMBNAIL_HEIGHT + THUMBNAIL_SPACING);

        // 检查是否点击在缩略图上（而不是间隙）
        int in_thumbnail_x = (relative_x % (THUMBNAIL_WIDTH + THUMBNAIL_SPACING)) < THUMBNAIL_WIDTH;
        int in_thumbnail_y = (relative_y % (THUMBNAIL_HEIGHT + THUMBNAIL_SPACING)) < THUMBNAIL_HEIGHT;

        if (col < GALLERY_COLS && row < GALLERY_ROWS && in_thumbnail_x && in_thumbnail_y)
        {
          int photo_index = g_current_page * (GALLERY_COLS * GALLERY_ROWS) + row * GALLERY_COLS + col;

          if (photo_index < g_photo_count)
          {
            char photo_path[512];
            snprintf(photo_path, sizeof(photo_path), "%s/%s",
                     GALLERY_DIR, g_photos[photo_index].filename);

            printf("全屏显示照片: %s\n", photo_path);
            gallery_show_fullscreen(photo_path);

            // 返回相册界面
            draw_gallery_ui(g_current_page);
          }
        }
      }
    }

    usleep(100000); // 100ms
  }

  printf("退出相册\n");
  return 0;
}
